<template>
  <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- 搜索框，对工段信息进行搜索 -->
    <div class="filter-container">
      <!-- clearable为添加清除输入数据 -->
      <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="listQuery.sectionId"
            style="width: 150px;margin-right:15px;margin-top:7px"
            class="filter-item"
            placeholder="请输入工段编号"
      ></el-input>
      <!-- style="width: 150px;margin-right:15px;margin-top:7px" -->
      <el-input
            @keyup.enter.native="getData"
            clearable
            v-model="listQuery.address"
            style="margin-right: 15px;margin-top:7px"
            :style="{ width: inputWid(listQuery.address) }"
            class="filter-item"
            placeholder="请输入工段地址"
      ></el-input>

      <el-select
        clearable
        v-model="listQuery.lineType"
        placeholder="请选择工段类型"
        style="width: 150px;margin-right:15px;margin-top:7px">
        <el-option :value="item" :label="item" v-for="(item,index) in lineTypeList" :key="index"/>
      </el-select>
      
      <!-- 2022/3/28 15:04 关键字搜索，输入工作中心搜索改为选择工作中心 -->
      <el-select 
            clearable
            v-model="listQuery.workCenter" 
            placeholder="请选择工作中心" 
            @focus="getCenterList" 
            style="width: 150px;margin-right:15px;margin-top:7px">
        <el-option :value="item" :label="item" v-for="(item,index) in this.centerList.data" :key="index"/>
      </el-select>

      <!-- <el-input
            @keyup.enter.native="handleFilter"
            clearable
            v-model="listQuery.workCenter"
            style="width: 150px;margin-right:15px;margin-top:7px"
            class="filter-item"
            placeholder="请输入工作中心"
      ></el-input> -->
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
    </div>

    
    <!-- 表单 -->
    <el-table :data="dealList" v-loading="listLoading" element-loading-text="拼命加载中"  stripe border fit highlight-current-row style="width: 100%">
        <el-table-column  label="序号" type="index" align="center"/>
        <el-table-column  label="线体简称" prop="sectionAbbreviation" align="center"/>
        <!-- <el-table-column  label="工段类型" prop="lineType" align="center"/> -->
        <el-table-column  label="工段类型" prop="lineType" align="center">
          <template slot-scope="scope">   
            <div class="fx">
              {{
               userInfo.roleId == 14 || scope.row.workCenter == '装配车间' || scope.row.workCenter == '总装车间' || scope.row.workCenter == '数控车间' || scope.row.workCenter == '喷涂车间'
                  ? scope.row.lineType
                  : ""
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column  label="工段编号" prop="sectionNo" align="center"/>
        <el-table-column  label="工段地址" prop="address" align="center"/>
        <el-table-column  label="工作中心" prop="workCenter" align="center"/>
        <el-table-column  label="工段长工号" prop="sectionManagerNumber" align="center"/>
        <el-table-column  label="QE工号" prop="qeNumber" align="center"/>
        <el-table-column  label="工艺工号" prop="technologist" align="center"/>
        <el-table-column  label="pmc工号" prop="pmcNumber" align="center"/>
        <el-table-column  label="设备人员工号" prop="grindingApparatus" align="center"/>
        <el-table-column  label="物流人员工号" prop="logistics" align="center"/>
        <el-table-column label="工段状态" prop="status" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status" size="medium" effect="dark" type="success">启用</el-tag>
            <el-tag v-else effect="dark" size="medium" type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <!-- 对工段进行修改与删除 -->
        <el-table-column  label="操作" align="center" width="230" v-if="userInfo.roleId != 37">
          <template slot-scope="scope" >
            <el-button v-if="userInfo.roleId == 14" size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
            <el-button v-if="scope.row.status == '1'" size="mini" type="info" @click="statusSwitch(scope.row)">禁用</el-button>
            <el-button v-else size="mini" type="success" @click="statusSwitch(scope.row)">启用</el-button>
            <el-button v-if="userInfo.roleId == 14" size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40,100,300,500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>


    <!-- 修改工段信息弹出表单 -->
    <el-dialog title="工段信息修改" :visible.sync="dialogFormVisible" width="700px">
    <el-form :model="modifyform"  ref="form" :rules="rules">
      <el-form-item label="工段类型" :label-width="formLabelWidth" v-if="userInfo.roleId == 9 || userInfo.roleId == 14 || modifyform.workCenter == '装配车间'|| modifyform.workCenter == '总装车间' || modifyform.workCenter == '喷涂车间'">
        <el-select v-model="modifyform.lineType" placeholder="请选择工段类型" style="width:400px">  
          <el-option :value="item" :label="item" v-for="(item,index) in lineTypeList" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="线体简称" :label-width="formLabelWidth" prop="sectionAbbreviation">
        <el-input v-model="modifyform.sectionAbbreviation" style="width:400px" />
      </el-form-item>
      <el-form-item label="工段编号" :label-width="formLabelWidth">
        <el-input v-model="modifyform.sectionNo" :disabled="true" style="width:400px"/>
      </el-form-item>
      <el-form-item label="工段地址" :label-width="formLabelWidth">
        <el-input v-model="modifyform.address" style="width:400px" />
      </el-form-item>
      <el-form-item label="工作中心" :label-width="formLabelWidth">
        <el-select v-model="modifyform.workCenter" placeholder="请选择工作中心" @focus="getCenterList" style="width:400px">
          <el-option :value="item" :label="item" v-for="(item,index) in this.centerList.data" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="工段长工号" :label-width="formLabelWidth">
        <el-input v-model="modifyform.sectionManagerNumber" style="width:400px" />
      </el-form-item>
      <el-form-item label="QE人员工号" :label-width="formLabelWidth">
        <el-input v-model="modifyform.qeNumber" style="width:400px" />
      </el-form-item>
      <el-form-item label="工艺人员工号" :label-width="formLabelWidth">
        <el-input v-model="modifyform.technologist" style="width:400px" />
      </el-form-item>
      <el-form-item label="PMC人员工号" :label-width="formLabelWidth">
        <el-input v-model="modifyform.pmcNumber" style="width:400px" />
      </el-form-item>
      <el-form-item label="设备人员工号" :label-width="formLabelWidth">
        <el-input v-model="modifyform.grindingApparatus" style="width:400px" />
      </el-form-item>
      <el-form-item label="物流人员工号" :label-width="formLabelWidth">
        <el-input v-model="modifyform.logistics" style="width:400px" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="modifyWorkSec('form')">确 定</el-button>
    </div>
    </el-dialog>
  </div>
</template>

<script>
import { checkWorkSecInfo,deleteWorkSecInfo,changeWorkSecInfo, WorkStatusSwitch, getCenter } from '../../api/workSection.js'
export default {
  name:'check_WorkSection',
    data() {
      return {
        loading: false,
        listQuery: {                          // 传入后台的搜索内容
          sectionId: '',                      //工段编号
          address: '',                        //工段地址
          workCenter: '',                     //工作中心
          page: 1,
          limit: 10,
          lineType: ''
        },
        modifyform: {     
          lineType:'',                    //
          sectionId: '',
          sectionNo: '',
          address: '',
          sectionAbbreviation: '',
          workCenter: '',
          sectionManagerNumber: '',
          qeNumber: '',
          sectionId: '',
          pmcNumber: '',
          grindingApparatus: '',
          technologist: '',
          logistics: ''
        },
        rules: {
            sectionAbbreviation: [
              { required: true, message: '请输入线体简称', trigger: 'blur' }
            ],
          },
        lineTypeList: [
          '组件',
          '装配',
          '包装',
          '数控',
          '喷涂'
        ],
        centerList: '',                       //获取工作中心的列表
        total: 0,                            //数据的总条数
        dealList: [],                         //table显示的信息
        // 弹框显示的判断条件
        dialogFormVisible: false,
        // 弹框内部组件的宽度设定
        formLabelWidth: '100px',
        listLoading: false,                    //加载动画控制
        userInfo: this.$store.state.user.userInfo,
      }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '170px'
            } else {
              return (170 + (String(value).length-10)*13) + 'px'
            }
        }
      }
    },
    methods: {
      // 搜索按钮定义的函数
      async handleFilter() {
        this.listLoading = true
        let query = Object.assign({},this.listQuery)
        // 暂时去掉，问题：当条件为空，切换页数为6（任意数）时，再通过选择员工部门查询，查询后的页码还是原来的6，切换页数永远是1。
        // if(query.sectionId == '' &&
        //    query.address == '' &&
        //    query.workCenter == '' 
        // ) {
        //   console.log('搜索内容不为空')
        // } else {
        //   query.page = 1
        // }
        query.lineType = query.lineType == '组件'?1:
                         query.lineType == '装配'?2:
                         query.lineType == '包装'?3:
                         query.lineType == '数控'?4:
                         query.lineType == '喷涂'?5:''
        const {data} = await checkWorkSecInfo(query)
        data.records.forEach(item => {
          item.lineType = item.lineType == 1?'组件':
                          item.lineType == 2?'装配':
                          item.lineType == 3?'包装':
                          item.lineType == 4?'数控':
                          item.lineType == 5?'喷涂':''
        });
        this.dealList = data.records
        this.total = data.total
        this.listLoading = false
      },
      // 获取工作中心
      async getCenterList() {
        if(this.centerList) return
        const data = await getCenter()
        this.centerList = data
      },
      modifyWorkSec(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.onSubmit()
            } else {
              return false
            }
          })
        },
      // 将弹框修改后的工段信息传入后台，并且消息提示是否修改成功
      async onSubmit() {
        this.dialogFormVisible = false
        let query = Object.assign({},this.modifyform)
        query.lineType = query.lineType == '组件'?1:
                         query.lineType == '装配'?2:
                         query.lineType == '包装'?3:
                         query.lineType == '数控'?4:
                         query.lineType == '喷涂'?5: 0
        // if(this.modifyform.workCenter != '数控车间' || this.modifyform.workCenter != 'EMS总装车间'){
        //   delete query.grindingApparatus
        //   delete query.logistics
        // }
        const data = await changeWorkSecInfo(query)
        if(data.code == '1'){
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.handleFilter()
        } else {
          this.$message({
            message: '修改失败',
            type: 'warning'
          })
        }
      },
    // 点击修改按钮，将table表的内容传入弹框内部的表单
    // item为一行的表单数据，为一个对象
    handleEdit(item) {
      this.modifyform = Object.assign({},item)
      this.dialogFormVisible = true
    },
    // 改变工段的状态函数，关闭或者开启
    async statusSwitch(item) {
      const data = await WorkStatusSwitch({sectionId: item.sectionId,status: item.status == '1' ? '0' : '1'})
      this.handleFilter()
    },
    // 删除用户按钮,使用elementui的messageBox弹框组件
    handleDelete(index,row) {
      this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
          let res = await deleteWorkSecInfo({sectionId: row.sectionId})
          this.dealList.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        }).catch(() => {
          this.$message({
            type: 'info', 
            message: '已取消删除'
          })
        })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.handleFilter()
    },
     handleCurrentChange(val) {
      this.listQuery.page = val
      this.handleFilter()
    },
    getData() {
      this.listQuery.page = 1
      this.listQuery.limit = 10
      this.handleFilter()
    },
    // 导出excel
    async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          query.lineType = query.lineType == '组件'?1:
                         query.lineType == '装配'?2:
                         query.lineType == '包装'?3:
                         query.lineType == '数控'?4:
                         query.lineType == '喷涂'?5:''
          let arr = await checkWorkSecInfo(query)
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          arr.data.records.forEach(item => {
          item.lineType = item.lineType == 1?'组件':
                          item.lineType == 2?'装配':
                          item.lineType == 3?'包装':
                          item.lineType == 4?'数控':
                          item.lineType == 5?'喷涂':''
        });
          const { header, data } = this.transformDat(this.setSort(arr.data.records))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '工段查询列表', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        transformDat(res) {
          const mapInfo = {
            sectionAbbreviation: '线体简称',
            lineType: '工段类型',  ///??
            sectionNo: '工段编号',
            address: '工段地址',
            workCenter: '工作中心',
            sectionManagerNumber: '工段长工号',
            qeNumber: 'QE工号',
            technologist: '工艺工号',
            pmcNumber: 'pmc工号',
            grindingApparatus: '设备人员工号',
            logistics: '物流人员工号',
            status: '工段状态',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              sectionAbbreviation: item.sectionAbbreviation,
              lineType: ['装配车间', '总装车间', '数控车间', '喷涂车间'].includes(item.workCenter) ? item.lineType : '',
              sectionNo: item.sectionNo,
              address: item.address,
              workCenter: item.workCenter,
              sectionManagerNumber: item.sectionManagerNumber,
              qeNumber: item.qeNumber,
              technologist: item.technologist,
              pmcNumber: item.pmcNumber,
              grindingApparatus: item.grindingApparatus,
              logistics: item.logistics,
              status: item.status ? '启用' : '禁用',
            }
            arr1.push(obj)
          })
          return arr1
        },
  },
  // 在生命周期函数调用"搜索"按钮绑定的函数，显示已有的数据
  mounted() {
    this.handleFilter();
  },
}
</script>

<style>

</style>